package com.bsoft.wx.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bsoft.wx.execption.EmosExection;
import com.bsoft.wx.mapper.TbUserMapper;
import com.bsoft.wx.pojo.TbUser;
import com.bsoft.wx.service.TbUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hdh
 * @since 2023-01-11
 */
@Service
@Slf4j
@Scope("prototype")
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {
    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;
    @Autowired
    private TbUserMapper tbUserMapper;


    private String getOpeId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openid = json.getStr("openid");
        if (openid == null || openid.length() == 0) {
            throw new RuntimeException("临时登录凭证错误");
        }
        return openid;
    }


    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
        //如果注册码为000000 为管理员 注册
        if (registerCode.equals("000000")) {
            //是否存用户
            boolean bool = tbUserMapper.haveRootUser1();
            if (!bool) {
                String openId = getOpeId(code);
                HashMap param = new HashMap();
                param.put("openId", openId);
                param.put("nickname", nickname);
                param.put("photo", photo);
                param.put("role", "[0]");  //超级管理员 0
                param.put("status", 1);  //在职有效
                param.put("createTime", new Date());
                param.put("root", true);

                tbUserMapper.insert(param);
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("open_id", openId);
                queryWrapper.eq("status", 1);
                TbUser tbUser = (TbUser) baseMapper.selectList(queryWrapper).get(0);
                return tbUser.getId();


            } else {
                throw new EmosExection("无法绑定超级管理员账户");
            }
        } else {
            //普通员注册
        }
        return 0;
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        Set<String> permissions = tbUserMapper.searchUserPermissions(userId);
        return permissions;
    }

    @Override
    public Integer login(String code) {
        //根据code 判断openid
        String openId = getOpeId(code);
        Integer id = tbUserMapper.searcherByOpenId(openId);
        if (id == null) {
            throw new EmosExection("账户不存在");
        }
        //todo 从消息队列中接收数据 转移到消息表
        return id;
    }

    @Override
    public TbUser searchById(int userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", userId);
        queryWrapper.eq("status", 1);
        TbUser tbUser = baseMapper.selectOne(queryWrapper);
        return tbUser;
    }
}
